﻿using Sunny.UI;
using System;
using System.IO.Pipes;
using System.IO;
using System.Threading;
using CoreShop.Model.FromBody;
using CoreShop.Library;
using System.Linq;
using CoreShop.App.Units;
using CoreShop.Model;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Runtime.InteropServices.ComTypes;
using CoreShop.Services.Services.Report;
using CoreShop.Services;
using SqlSugar;
using NPOI.HSSF.Record.Chart;
using NPOI.SS.Formula.Functions;

namespace CoreShop.App
{
    public partial class fpgOrderList : UIPage
    {
        public int mPageIndex = 0;
        PosReportRequest mRptRequest;
        public fpgOrderList()
        {
            InitializeComponent();
            LoadComboxData();
        }

        private void LoadComboxData()
        {
            #region 加载支付方式
            this.userId.Items.Clear();
            List<sysuser> user = new sysuserServices().GetList().Where(p => p.deleted == false && p.state == 0).ToList();
            userId.DataSource = user;
            userId.DisplayMember = "userName";
            userId.ValueMember = "id";
            userId.Text = "";
            userId.SelectedValue = 0;
            #endregion
        }

        private void fpgOrderList_ReceiveParams(object sender, UIPageParamsArgs e)
        {
            mPageIndex = 1;
            var rptRequest = e.Value as PosReportRequest;
            if (rptRequest.type == (int)GlobalEnumVars.ReportRequest.Query)
            {
                LoadData(rptRequest);
            }
            else
            {
                ExportData();
            }
        }

        private void ExportData()
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "Execl files (*.xls)|*.xls";
            saveFileDialog.FilterIndex = 0;
            saveFileDialog.RestoreDirectory = true;
            saveFileDialog.Title = "Export Excel File To";
            saveFileDialog.ShowDialog();
            string fileName = saveFileDialog.FileName;
            if (fileName == "") return;
            Dictionary<string, DataGridView> gridViews = new Dictionary<string, DataGridView>();
            gridViews.Add("支付明细", dgvPayList);
            if (ExportUtil.NPOIExportForDataGridview(gridViews, fileName))
            {
                MessageBox.Show("导出Excel成功！");
            }
        }

        private Expressionable<corecmsfoodordermaster, corecmsuser, sysuser, corecmsfoodorderclass> GetExpressionable(PosReportRequest posReport)
        {
            string str = this.numberText.Text;
            var where = Expressionable.Create<corecmsfoodordermaster, corecmsuser, sysuser, corecmsfoodorderclass>();

            if (posReport.starTime != null)
                where = where.And((a, u, su, c) => a.orderDate > posReport.starTime);

            if (posReport.endTime != null)
                where = where.And((a, u, su, c) => a.orderDate < posReport.endTime);

            long sysUserId = CommFunc.ConvertToBigInt(userId.SelectedValue);
            if (sysUserId > 0)
                where = where.And((a, u, su, c) => a.sysUserId == sysUserId);

            if (!string.IsNullOrEmpty(str))
            {
                var classModel = new corecmsfoodorderclassServices().AsQueryable().Where(p => p.classNumber == str).First();
                if (classModel != null)
                    where = where.And((a, u, su, c) => a.classId == classModel.id);
                else
                    where = where.And((a, u, su, c) => (a.orderNo.Contains(str) || a.number.Contains(str) || u.mobile.Contains(str) || u.cardNo.Contains(str)));
            }

            return where;
        }

        /// <summary>
        ///销售统计
        /// </summary>
        private void LoadData(PosReportRequest posReport)
        {
            int count = 0;         
            List<corecmsfoodsalemaster> lstSource = new corecmsfoodordermasterServices().SelectByOrdertype(ref count, mPageIndex, btnPg4.PageSize, GetExpressionable(posReport));
            btnPg4.TotalCount = count;
            mRptRequest = posReport;
            this.dgvPayList.AutoGenerateColumns = false;
            this.dgvPayList.DataSource = lstSource;
            //uiDataGridViewFooter1.DataGridView = sumRow;
            //设置统计绑定的表格
            PageTotal.DataGridView = dgvPayList;
            PageTotal["orderNo"] = string.Format("合计：{0}条", lstSource.Count);
            PageTotal["sumAmount"] = CommFunc.ConvertToString(lstSource.Sum(p=>p.sumAmount));
            PageTotal["sumQuantity"] = CommFunc.ConvertToString(lstSource.Sum(p => p.sumQuantity));
            PageTotal["sumRealAmount"] = CommFunc.ConvertToString(lstSource.Sum(p => p.sumRealAmount));
            PageTotal["sumDiscountAmount"] = CommFunc.ConvertToString(lstSource.Sum(p => p.sumDiscountAmount));
            PageTotal["sumTaskAmount"] = CommFunc.ConvertToString(lstSource.Sum(p => p.sumTaskAmount));
            PageTotal["sumFeedAmount"] = CommFunc.ConvertToString(lstSource.Sum(p => p.sumFeedAmount));
            PageTotal["sumReduceAmount"] = CommFunc.ConvertToString(lstSource.Sum(p => p.sumReduceAmount));
            PageTotal["sumAllAmount"] = CommFunc.ConvertToString(lstSource.Sum(p => p.sumAllAmount));
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            userId.SelectedValue = 0;
            userId.Text = "";            
        }

        private void btnPg4_PageChanged(object sender, object pagingSource, int pageIndex, int count)
        {
            mPageIndex = pageIndex;
            LoadData(mRptRequest);
        }
    }
}